package com.example.aidlclientdemo;

import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

/**
 * @author 猿小蔡
 * @since 2025/6/28
 */
public class SocketClient {
    private Socket socket;
    private PrintWriter out;
    private BufferedReader in;

    public void connect(String serverIp, int port, final MessageCallback callback) {
        new Thread(() -> {
            try {
                socket = new Socket(serverIp, port);
                out = new PrintWriter(socket.getOutputStream(), true);
                in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

                Log.i("CLIENT", "Connected to server");
                callback.onConnected();

                // 接收消息线程
                new Thread(() -> {
                    try {
                        String response;
                        while ((response = in.readLine()) != null) {
                            final String msg = response;
                            callback.onMessageReceived(msg);
                        }
                    } catch (IOException e) {
                        Log.e("CLIENT", "Receive error: " + e.getMessage());
                        callback.onDisconnected();
                    }
                }).start();

            } catch (IOException e) {
                Log.e("CLIENT", "Connection error: " + e.getMessage());
                callback.onConnectionFailed();
            }
        }).start();
    }

    public void sendMessage(String message) {
        if (out != null && !out.checkError()) {
            out.println(message);
            Log.i("CLIENT", "Sent: " + message);
        }
    }

    public void disconnect() {
        try {
            if (in != null) {
                in.close();
            }
            if (out != null) {
                out.close();
            }
            if (socket != null) {
                socket.close();
            }
        } catch (IOException e) {
            Log.e("CLIENT", "Disconnect error: " + e.getMessage());
        }
    }

    public interface MessageCallback {
        void onConnected();
        void onConnectionFailed();
        void onDisconnected();
        void onMessageReceived(String message);
    }
}
